<?php

namespace App\Kuafu\Robot\Service;

use App\Kuafu\Base\Service\BaseService;
use App\Kuafu\Robot\Enum\RmsRobotCodeEnum;
use GuzzleHttp\Client as GuzzleClient;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Facades\Redis;

class RmsBotService extends BaseService
{
    public function daily()
    {

//        $dbData =
        $msg = self::sendDailyMessage();

        dd($this->sendGroupMessage($msg));

    }

    public function getRobot()
    {
        if ('prod' == config('app.env')) {
            return [
                'appId'     => 'cli_a12887c737b8900d',
                'appSecret' => 'xXRyhS9jb1EisEvG4jwrCbcUHXOv1mmJ'
            ];
        } else {
            return [
                'appId'     => 'cli_a12887c737b8900d',
                'appSecret' => 'xXRyhS9jb1EisEvG4jwrCbcUHXOv1mmJ'
            ];
        }
    }

    public function getGroupInfo()
    {
        if ('prod' == config('app.env')) {
            return [
                'chat_id' => 'oc_8623f2934497a0ae408f0208ab100096'
            ];
        } else {
            return [
                'chat_id' => 'oc_8623f2934497a0ae408f0208ab100096'
            ];
        }
    }

    /**
     * 获取token
     */
    public function getTenantAccToken($appid, $appSecret)
    {
        $tenantToken = Redis::get('RMS_ROBOT:' . $appid);
        if (!$tenantToken) {
            $client      = new GuzzleClient();
            $body        = ['app_id' => $appid, 'app_secret' => $appSecret];
            $body        = json_encode($body);
            $url         = 'https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal';
            $response    = $client->request("POST", $url, ['body' => $body, 'timeout' => 10]);
            $response    = $response->getBody()->getContents();
            $responseArr = json_decode($response, true);
            Redis::setex('RMS_ROBOT' . $appid, $responseArr['expire'],
                $responseArr['tenant_access_token']);
            return $responseArr['tenant_access_token'];
        } else {
            return $tenantToken;
        }
    }

    public function sendGroupMessage(array $data)
    {
        $group = $this->getGroupInfo();
        return $this->sendMessage($group['chat_id'], 'chat_id', $data, 'interactive');
    }

    /**
     * 发送消息
     * @param string $receiveId 依据receive_id_type的值，填写对应的消息接收者id
     * @param string $receiveType open_id/user_id/union_id/email/chat_id
     * @param array $data 消息内容
     * @param string $messageType 消息类型 包括：text、post、image、file、audio、media、sticker、interactive、share_chat、share_user
     * @throws GuzzleException
     */
    public function sendMessage(
        string $receiveId,
        string $receiveType,
        array $data,
        string $messageType
    ) {
        if (!$receiveId) {
            return [];
        }
        $url    = 'https://open.feishu.cn/open-apis/im/v1/messages?receive_id_type=' . $receiveType;
        $client = new GuzzleClient();
        $body   = [
            'receive_id' => $receiveId,
            'content'    => json_encode($data),
            'msg_type'   => $messageType
        ];

        $body     = json_encode($body);
        $response = $client->request('POST', $url, [
            'body'        => $body,
            'headers'     => [
                'Content-Type'  => "application/json; charset=utf-8",
                'Authorization' => self::getAccToken()
            ],
            'timeout'     => 10,
            'http_errors' => false,
        ]);
        $response = $response->getBody()->getContents();
        return json_decode($response, true);
    }


    public function getAccToken()
    {
        $robot    = self::getRobot();
        $accToken = 'Bearer ' . self::getTenantAccToken($robot['appId'], $robot['appSecret']);
        return $accToken;
    }

    public function sendDailyMessage()
    {
        $data = [
            'config'   => [
                'wide_screen_mode' => true,
                'update_multi'     => true,
            ],
            'header'   => [
                'template' => 'blue',
                'title'    => [
                    'content' => '订单统计',
                    'tag'     => 'plain_text'
                ]
            ],
            'elements' => [
                [
                    "tag"   => "div",
                    "text"  => [
                        "tag"     => "lark_md",
                        "content" => "查询日期",
                    ],
                    "extra" => [
                        "tag"          => "date_picker",
                        "placeholder"  => [
                            "tag"     => "plain_text",
                            "content" => "请选择日期",
                        ],
                        "initial_date" => date('Y-m-d')
                    ]
                ],
                [
                    "tag"     => "markdown",
                    "content" => "堂食订单自查 BOT\r昨日堂食总订单统计:\r总有效订单量: 20140 单\r总有效店铺数: 338 家\r总订单最大店铺: 夸父炸串（嘉兴星河CoCoCity店）, 单量为: 333 单"
                ]
            ]
        ];
        return $data;
    }

    public function getDbData()
    {
        $data = [
            ''
        ];
    }

    public static function handleMsg(string $message)
    {
        $content = json_decode($message, 1);
        if (!is_array($content)) {
            return ['', ''];
        }

        $msgArr = explode(' ', $content['text'] ?? '');

        if (strpos($msgArr[0], '/') === 0) {
            $commandStr = $msgArr[0];
            unset($msgArr[0]);
            $params = implode(' ', $msgArr);
            return [$commandStr, $params];
        } else {
            return ['', ''];
        }
    }


}
